import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import * as echart from 'echarts';
import { setOptionFun } from './utils';
export default forwardRef(
  ({ style = {}, option, onFinished, onRendered, chartClick }, ref) => {
    const [Base64, setBase64] = useState(null);
    // 图表容器
    const chartContainer = useRef();
    // 图表实例
    const chartInstance = useRef(null);
    // 绘制方法
    const drawChartFun = (_option) => {
      initInstance();
      if (chartInstance?.current) {
        chartInstance.current.setOption(_option, true);
        hanlder();
      }
    };
    // 初始化实例
    const initInstance = () => {
      console.log('进来渲染了');
      // 创建图表实例
      if (chartContainer.current && !chartInstance.current && echart?.init) {
        chartInstance.current = echart.init(chartContainer.current);

        // 图表的点击事件
        chartInstance.current.on('click', function (params) {
          // 此处一般写：click事件触发后的回调，来完成额外的功能
          let seriesObj = chartInstance.current.getOption(); //图表object对象
          chartClick &&
            chartClick({
              index: params?.dataIndex,
              seriesObj,
              name: params?.name,
              datas: params?.value,
            });
        });
      }
    };
    // 获取图像
    const getChartImg = (params = {}) => {
      if (chartInstance.current) {
        return chartInstance.current.getDataURL({
          type: 'png',
          backgroundColor: 'transparent',
          ...params,
        });
      }
      return '';
    };

    // 销毁
    const dispose = () => {
      chartInstance?.current.resize();
    };
    const resize = () => {
      chartInstance?.current.resize();
    };
    useImperativeHandle(ref, () => {
      getChartImg, dispose, resize;
    });

    const hanlder = () => {
      chartInstance?.current.resize();
    };
    useEffect(() => {
      if (option) {
        chartInstance?.current?.clear();
        drawChartFun(setOptionFun(option));
        if (setBase64) {
          setTimeout(() => {
            setBase64(getChartImg());
          }, 1000);
        }
      }
    }, [option]);

    useEffect(() => {
      // 初始化创建实例
      initInstance();
      // 监听屏幕变化，重绘图表
      window.addEventListener('resize', hanlder);
      return () => {
        window.removeEventListener('resize', hanlder);
      };
    }, []);
    return (
      <div
        style={{ height: '100%', width: '100%', minHeight: 300, ...style }}
        ref={chartContainer}
      ></div>
    );
  },
);
